#!/usr/bin/python
## This is a helper program to run random scripts and pass arguments to them regardless of the type, used mainly with the Kate editor
## Copyright (C) Ahmed Waheed <oneofone@gmail.com>
## This program is published under a MIT license

from subprocess import call
from shlex import split as shsplit
import sys,os
ext_map = {
	'.py': '/usr/bin/python',
	'.py3': '/usr/bin/python3',
	'.pl': '/usr/bin/perl',
	'.rb': '/usr/bin/ruby',
	'.php': '/usr/bin/php',
	'.html': '/usr/bin/konqueror'
}
default_ = ['/bin/sh']

if len(sys.argv) < 3:
	sys.stderr.write("usage : %s dir script [args]\n" % sys.argv[0]);
	sys.exit(1)

os.chdir(sys.argv[1])
cmd = sys.argv[2]
app = None

with open(cmd, 'rb') as f:
	ln = f.readline()
	if ln[0:2] == '#!':
		app = shsplit(ln[2:]) #support things like #!/usr/bin/perl -W, etc

if app is None:
	ext = cmd.rfind('.')
	if ext == -1:
		app = default_
	else:
		app = [ext_map.get(cmd[ext:], default_)]

try:
	exe = app + [cmd] + sys.argv[3:]
	ret = call(exe)
	sys.stdout.write("\n[%s] returned : %d\n" % (' '.join(exe), ret))
finally:
	try:
		input("Press any key to exit.")
	except:
		pass